<template>
     <div class="app-container">
        <el-card class="export-card form-card" >
            <template #header>
                <span>搜索</span>
            </template>
            <el-form label-position="left" label-width="110" @keyup.enter.native="handleSearch">
                    <el-form-item label="智能搜索" >
                        <el-input placeholder="请输入关键词" v-model="queryParams.key" clearable  ></el-input>
                    </el-form-item>
                    <el-form-item label="合同日期">
                        <el-date-picker
                            v-model="queryParams.signTime"
                            type="daterange"
                            unlink-panels
                            clearable
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="YYYY-MM-DD"
                        />
                    </el-form-item>

                    <el-form-item label="合同总金额">
                        <div style="display: flex; align-items: flex-end;">
                            <MoneyRangeInput v-model="queryParams.hetongzongjine"></MoneyRangeInput> <span style="flex:50px;margin-left: 10px;">万元</span>
                        </div>
                    </el-form-item>
                    <el-form-item label="存储位置">
                        <el-tree-select
                            v-model="queryParams.cabinetId"
                            :data="cabinetData"
                            filter 
                            @change="handleSelectChange"
                            ref="CabinetTreeRef"  
                            clearable
                            node-key="id"
                            :render-after-expand="false"
                            check-strictly
                            :props="{ label: 'name', children: 'sub', value: 'id' }"
                            style="width: 100%"
                        >
                          
                        </el-tree-select>
                                            
                        <!-- <el-input placeholder="请输入" v-model="queryParams.cabinet" clearable  ></el-input> -->
                        <!-- <InputSelect 
                            v-model="queryParams.cabinetDoorId"
                            :options="cabinetTableData?.cabinets"
                            label-key="name"
                            placeholder="请选择"
                        ></InputSelect> -->
                        <!-- <el-select v-model="queryParams.cabinetDoorId" placeholder="请选择" clearable filterable >
                            <el-option v-for="(item,index) in " :key="index"  :label="item.name" :value="item.id" ></el-option>
                        </el-select> -->
                    </el-form-item>
                     <el-form-item label="产品名称">
                        <!-- <el-input placeholder="请输入" v-model="queryParams.productName" clearable  ></el-input> -->
                        <InputSelect 
                            v-model="queryParams.productName"
                            :options="cabinetTableData?.produceNames"
                            placeholder="请输入或选择"
                        ></InputSelect>
                    </el-form-item>
                    <el-form-item label="供应商">
                        <!-- <el-input placeholder="请输入" v-model="queryParams.partB" clearable  ></el-input> -->
                        <InputSelect 
                            v-model="queryParams.partB"
                            :options="cabinetTableData?.partBs"
                            placeholder="请输入或选择"
                        ></InputSelect>
                    </el-form-item>
                      
                    <el-form-item label="生产厂家">
                        <!-- <el-input placeholder="请输入" v-model="queryParams.brand" clearable  ></el-input> -->
                        <InputSelect 
                            v-model="queryParams.produceManuName"
                            :options="cabinetTableData?.produceManufacturers"
                            placeholder="请输入或选择"
                        ></InputSelect>
                    </el-form-item>
                    <el-form-item label="科室">
                        <el-input placeholder="请输入" v-model="queryParams.deptName" clearable  ></el-input>
                        <!-- <InputSelect 
                            v-model="queryParams.deptId"
                            :options="cabinetTableData?.cabinets"
                            placeholder="请输入或选择"
                        ></InputSelect> -->
                    </el-form-item>
                    <el-form-item label="资金来源">
                        <el-select v-model="queryParams.plinarySource" placeholder="请选择" clearable  remote>
                            <el-option :label="'院资'"  :value="'院资'" ></el-option>
                            <el-option :label="'财政拨款'"  :value="'财政拨款'" ></el-option>
                            <el-option :label="'贴息贷款'"  :value="'贴息贷款'" ></el-option>
                            <el-option :label="'科研'"  :value="'科研'" ></el-option>
                        </el-select>
                    </el-form-item>
                    <br>
                    <div style="text-align: center;">
                        <el-button type="primary" style="width: 70%;" size="large" @click="handleSearch">开始检索</el-button>
                    </div>
            </el-form>
        </el-card>
        <el-card class="export-card">
            <template #header>
                <span>检索结果</span>
            </template>
            <el-table 
                :data="TableData" 
                style="width: 100%;height: 75vh;" 
                v-loading="loading"
            >
                <el-table-column label="序号" min-width="80">
                    <template #default="scope">{{scope.$index + 1}}</template>
                </el-table-column>
                <el-table-column prop="name" label="项目名称" show-overflow-tooltip min-width="180"/>
                <el-table-column prop="cabinetBoxNames" label="存储位置" min-width="180" :sort-method="sortByCabinetBoxNames"  :sortable="true">
                    <template #default="scope">
                        <el-tooltip :content="scope.row.cabinetRemark" :disabled="!scope.row.cabinetRemark" >
                            {{scope.row.cabinetBoxNames}}
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column prop="signTime" label="合同日期" min-width="180" :sort-method="sortBySignTime"  :sortable="true" />
                <el-table-column prop="produceNames" label="产品" min-width="180">
                    <template #default="scope">
                        {{scope.row.produceNames || '--'}}
                    </template>
                </el-table-column>
                <el-table-column prop="zongjine" label="总金额" min-width="180" :sort-method="sortByZongjine"  :sortable="true">
                    <template #default="scope">
                        {{scope.row.zongjine || '--'}}
                    </template>
                </el-table-column>
                <!-- <el-table-column prop="unitPrice" label="总价" min-width="180">
                    <template #default="scope">
                        {{scope.row.totalPrice || '--'}}
                    </template>
                </el-table-column> -->
                <!-- <el-table-column prop="totalPrice" label="使用科室" min-width="180">
                    <template #default="scope">
                        {{ '--'}}
                    </template>
                </el-table-column> -->
                <el-table-column  label="操作" width="160" fixed="right">
                    <template #default="scope">
                        <el-button type="text" @click="handleView(scope.row)">详情</el-button>
                        <!-- <el-button type="text" @click="handleProductDetail(scope.row)">合同详情</el-button> -->
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <el-dialog :title="'详情'" v-model="dialogVisible" width="900px" :before-close="handleClose">
            <div v-loading="dialogLoading">
                <el-form>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="供应商">
                                <span :class="{'textActive': queryParams.partB && queryParams.partB == dialogObj.partB}">
                                    {{ dialogObj?.partB || '--' }}
                                </span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="联系人">
                                <span :class="{'textActive': queryParams.representativeB && queryParams.representativeB === dialogObj.representativeB}">
                                    {{ dialogObj?.representativeB || '--' }}
                                </span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="联系电话">
                                {{ dialogObj?.telB || '--' }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="合同日期">
                                {{ dialogObj?.signTime || '--' }}
                            </el-form-item>
                        </el-col>
                        <br>
                        <el-col :span="12">
                            <el-form-item label="使用科室">
                                {{ dialogObj?.department || '--' }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="资金来源">
                                {{ dialogObj?.fundingSource || '--' }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="合同总金额">
                                {{ dialogObj?.zongjine || '--' }}
                            </el-form-item>
                        </el-col>
                        <br>
                        <el-form-item label="产品"></el-form-item>
                        <el-table :data="ProductList" style="width: 100%" >
                            <el-table-column label="产品名称" min-width="180" >
                                <template #default="scope">
                                    <span :class="{'textActive': queryParams.productName && queryParams.productName === scope.row.name}">
                                        {{ scope.row.name || '--' }}
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column label="品牌" min-width="180" >
                                <template #default="scope">
                                    <span :class="{'textActive': queryParams.brand && queryParams.brand === scope.row.brand}">
                                        {{ scope.row.brand || '--' }}
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column label="规格型号" min-width="180" >
                                <template #default="scope">
                                    <span :class="{'textActive': queryParams.model && queryParams.model === scope.row.model}">
                                        {{ scope.row.model || '--' }}
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column label="数量" min-width="120" >
                                <template #default="scope">
                                    {{ scope.row.quantity || '--' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="单价" min-width="180" >
                                <template #default="scope">
                                    {{ scope.row.unitPrice || '--' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="总价" min-width="180" >
                                <template #default="scope">
                                    {{ scope.row.totalPrice || scope.row.totalPrice || '--' }}
                                </template>
                            </el-table-column>
                        </el-table>                        
                    </el-row>
                </el-form>
                <br>
                <el-table :data="PathList" style="width: 100%" >
                    <el-table-column label="检索文本" min-width="180" show-overflow-tooltip>
                        <template #default="scope">
                            <p v-html="scope.row.content"></p>
                        </template>
                    </el-table-column>
                    <el-table-column  label="操作" width="120">
                        <template #default="scope">
                            <el-button type="text" @click="handleDownLoad(scope.row)">预览</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { onUnmounted, ref, getCurrentInstance, onMounted } from 'vue';
import axios from 'axios';
import MoneyRangeInput from "./components/MoneyRangeInput.vue"
import InputSelect from "@/components/InputSelect/index.vue";
import { SearchDataCriteria, SearchQuery, projectDocumentGet, CabinetAllQuery } from "@/api/user.js"
import { ProjectTaskImages } from "@/api/project"
import { useRouter } from "vue-router";
const CabinetTreeRef = ref(null);
const { proxy } = getCurrentInstance();
const router = useRouter();
const loading = ref(false);
const cabinetLoading = ref(false);
 
const dialogVisible = ref(false);
const dialogLoading = ref(false);
const cabinetTableData = ref({
    cabinets: [],
    partBs: [],
    productNames: [],
    brands: [],
});
const PathList = ref([]);
const ProductList = ref([]);
// 档案柜 盒 tree 数据
const cabinetData = ref([]);

const queryParams = ref({
    key: '',
    total: 0,
});
const dialogObj = ref({});
const TableData = ref([]);
onMounted(async () => {
    if(localStorage.getItem('searchPageParams')){
        queryParams.value = JSON.parse(localStorage.getItem('searchPageParams'));
        handleSearch();
    }
    cabinetLoading.value = true;
    await getCabinetList();
    await getCabinetTree();
    cabinetLoading.value = false;
});


// 用 defineOptions 定义组件选项（模拟选项式 API 的路由守卫）
defineOptions({
  // 组件内路由守卫：进入前
  beforeRouteEnter(to, from, next) {
    // console.log('beforeRouteEnter 执行');
    // console.log(to, from, 'nextfffff');
    if(from.path != 'projectDigital/details'){
        setTimeout(() => {
            localStorage.removeItem('searchPageParams');
        }, 1500);
    }
    // 通过 next(vm => {}) 访问组件实例
    next();
  },
  // 组件内路由守卫：参数更新
  beforeRouteUpdate(to, from, next) {
    // console.log('beforeRouteUpdate 执行');
    next();
  },
  // 组件内路由守卫：离开前
  beforeRouteLeave(to, from, next) {
    // console.log('beforeRouteLeave 执行',to, from);
    // console.log(to, from, 'nextfffff');
    next();
  }
});
// 合同日期排序方法
const sortBySignTime = (a, b) => {
    const timeA = a.signTime;
    const timeB = b.signTime;

    // 1. 处理空值情况
    // a为空，b不为空 → a排后（返回1）
    if ((!timeA && timeA !== 0) && (timeB || timeB === 0)) {
        return 1;
    }
    // b为空，a不为空 → b排后（返回-1）
    if ((!timeB && timeB !== 0) && (timeA || timeA === 0)) {
        return -1;
    }
    // 两者都为空 → 位置不变
    if ((!timeA && timeA !== 0) && (!timeB && timeB !== 0)) {
        return 0;
    }

    // 2. 非空值按时间正常排序（转换为Date对象比较）
    const dateA = new Date(timeA).getTime(); // 转为时间戳（毫秒）
    const dateB = new Date(timeB).getTime();

    return dateA - dateB; // 升序（旧→新）；若需降序则改为 dateB - dateA
};


// 总金额排序方法
const sortByZongjine = (a, b) => {
    const amountA = a.zongjine;
    const amountB = b.zongjine;

    // 处理空值：空值排在最后
    if (amountA == null || amountA == undefined) return 1; // a空，a排后
    if (amountB == null || amountB == undefined) return -1; // b空，b排后

    // 非空数字直接比较
    return amountA - amountB; // 升序（小→大）；降序用 amountB - amountA
}


// 存储位置排序方法
const sortByCabinetBoxNames = (a, b) => {
    const nameA = a.cabinetBoxNames || '';
    const nameB = b.cabinetBoxNames || '';
// 解析“X柜Y层Z盒”为数字对象
  const parseLocation = (loc) => {
    const match = loc.match(/(\d+)柜(\d+)层(\d+)盒/);
    if (match) {
      return {
        cabinet: parseInt(match[1]), // 柜号
        layer: parseInt(match[2]),   // 层号
        box: parseInt(match[3])      // 盒号
      };
    }
    // 格式不匹配时返回默认值（可根据需求调整）
    return { cabinet: 0, layer: 0, box: 0 };
  };

  const locA = parseLocation(nameA);
  const locB = parseLocation(nameB);

  // 1. 先比较柜号
  if (locA.cabinet !== locB.cabinet) {
    return locA.cabinet - locB.cabinet;
  }
  // 2. 柜号相同，比较层号
  if (locA.layer !== locB.layer) {
    return locA.layer - locB.layer;
  }
  // 3. 层号相同，比较盒号
  return locA.box - locB.box;
};

// 获取 档案柜 盒 tree 数据
const getCabinetTree = async () => {
    let res = await CabinetAllQuery();
    if(res.errorCode == 0){
        cabinetData.value = res.data;
    }
}

const handleClose = () => {
    dialogVisible.value = false;
}

const getSearchData = async () => {
    loading.value = true;
    let res = await SearchQuery(queryParams.value);
    loading.value = false;
    if(res.errorCode == 0){
        TableData.value = res.data;
    }
   
}
// 递归获取节点的完整路径（父级 + 子级）
const getFullPath = (node) => {
    console.log(node);
    
  const path = [node.label]; // 先添加当前节点的名称
  let parent = node.parent;  // 获取父节点

  // 向上递归查找所有父节点
  while (parent && parent.label) {
    path.unshift(parent.label); // 将父节点名称添加到路径数组的前面
    parent = parent.parent;     // 继续查找上一级父节点
  }

  // 拼接所有节点名称（用“/”分隔，可自定义）
  return path.join('-');
};
const handleSearch = () => {
    getSearchData();
}
const handleView = async (row) => {
    localStorage.setItem('searchPageParams',JSON.stringify(queryParams.value));

    router.push({
        path:'/projectDigital/details',
        query:{
            id:row.id,
            [queryParams.value.key?'key':'']:queryParams.value.key || '',
            type: 'SearchProject'
        }
    })
    return 
    dialogVisible.value = true;
    dialogLoading.value = true;
    let res= await projectDocumentGet({
        projectId: row.id,
        key:queryParams.value.key 
    })
    dialogLoading.value = false;
    if(res.errorCode == 0){
        dialogObj.value = res.data.extract;
        if(res.data?.produces){
            ProductList.value = res.data.produces;
        }else{
            ProductList.value = [];
        }
        if(!res.data?.subPaths){
            PathList.value = [];
        }else{
            PathList.value = res.data.subPaths?.map(item=>{
                return {
                    imgUrl: item.imgUrl,
                    content: queryParams.value.key ?  item.content.replace(new RegExp(queryParams.value.key, 'g'), `<span style="color:red">${queryParams.value.key}</span>`) : item.content,
                }
            });
        }
    }
}

// 合同详情
const handleProductDetail =  (row) => {
    router.push({
        path:'/filingCabinet/boxdetail',
        query:{
            
            projectIds:[item.id],
            cabinetId:item.cabinetId,
            boxId:item.id,
        }
    })
}

const handleDownLoad = async (row) => {
    // downloadFile(path);
    // window.open('http://localhost:10899/file/download?fileId='+row.fileId);
    proxy.$ViewerApi([row.imgUrl]);
}
// 获取 科室 资金来源 供应商 等搜索下拉 数据
const getCabinetList = async () => {
    let res = await SearchDataCriteria()
    if(res.errorCode == 0){
        cabinetTableData.value = res.data;

    }
}

// 选中项变化时触发
const handleSelectChange = (selectedId) => {
    if (!selectedId) return;

    // 1. 获取选中的节点对象
    const selectedNode = CabinetTreeRef.value.getNode(selectedId); // 通过id获取节点  

    // 2. 递归收集所有子节点ID
    const allChildrenIds = [];
    console.log(selectedNode);
    if(!selectedNode.data.sub){
        allChildrenIds.push(selectedNode.data.id);
    }else{
        collectAllChildrenIds(selectedNode, allChildrenIds);
    }
    queryParams.value.boxIds = allChildrenIds;
    // console.log('选中节点的所有子类ID：', allChildrenIds);
    // 后续可根据需要处理allChildrenIds（如赋值给变量、发送请求等）
};

// 递归函数：收集节点的所有子节点ID
const collectAllChildrenIds = (node, resultArr) => {
  // 如果节点有子节点（sub数组）
  if (node.childNodes && node.childNodes.length > 0) {
    node.childNodes.forEach(childNode => {
      // 收集子节点的id
      if (childNode.data.id){
        resultArr.push(childNode.data.id);
      }
      // 递归收集孙子节点
      collectAllChildrenIds(childNode, resultArr);
    });
  }
};

</script>

<style lang="scss" scoped> 
.export-card{
    height: 100%;
    &+.export-card{
        flex: 1;
        margin-left: 15px;
        margin-top: 0;
    }
    &.form-card{
        flex: 0 auto;
        width: 450px;
    }
}
.textActive{
    color: red;
}
.app-container{
    display: flex;
    height: 100%;
    box-sizing: border-box;
}
</style>